<template>
  <template v-if="!item.meta?.hidden">
    <SideBarItemLink
      v-if="filterChildren.length <= 1 && !item.meta?.alwaysShow"
      :to="resolvePath(singleChildrenRoute.path)"
    >
      <el-menu-item :index="resolvePath(singleChildrenRoute.path)">
        <el-icon v-if="iconName">
          <svg-icon :icon-name="iconName"></svg-icon>
        </el-icon>
        <template #title> {{ singleChildrenRoute.meta?.title }}</template>
      </el-menu-item>
    </SideBarItemLink>
    <el-sub-menu class="subMenu" :index="item.path" v-else>
      <template #title>
        <el-icon v-if="iconName">
          <svg-icon :icon-name="iconName"></svg-icon>
        </el-icon>
        <span>{{ singleChildrenRoute.meta?.title }}</span>
      </template>
      <SideBarItem
        v-for="child in filterChildren"
        :key="child.path"
        :item="child"
        :base-path="resolvePath(child.path)"
      ></SideBarItem>
    </el-sub-menu>
  </template>
</template>

<script setup lang="ts" name="SideBarItem">
import type { RouteRecordRaw } from "vue-router"
import path from "path-browserify"
import { isExternal } from "@/utils/valiate"

const { item, basePath } = defineProps<{
  item: RouteRecordRaw
  basePath: string
}>()
// console.log("item", item)
// console.log("basePath", basePath)
// console.log("===========================")
const filterChildren = computed(() =>
  (item.children || []).filter((i) => !i.meta?.hidden)
)
const singleChildrenRoute = computed(() =>
  filterChildren.value.length === 1
    ? filterChildren.value[0]
    : { ...item, path: "" }
)
const iconName = computed(() => singleChildrenRoute.value.meta?.icon)
// console.log("title", title.value)
// console.log("filterChildren", filterChildren.value)
// console.log("singleChildrenRoute", singleChildrenRoute.value)

const resolvePath = (routePath: string) => {
  // console.log("routePath", routePath, typeof routePath)
  if (isExternal(routePath)) {
    return routePath
  }
  return path.join(basePath, routePath)
}
</script>

<style scoped lang="scss">
:deep(.el-menu-item) {
  @apply flex;
  &.is-active {
    color: #000000;
  }
}

a {
  text-decoration: none !important;
}
</style>
